package com.javastudy.liuhouse.jdbc18;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//使用数据库连接池 HikariCP
public class JdbcLianjieChi {
    //JDBC连接的URL,不同的数据库有不同的格式
    private String JDBC_URL = "jdbc:mysql://localhost:3306/learnjdbc?useSSL=false&characterEncoding=utf8";
    private String JDBC_USER = "root";
    private String JDBC_PASSWORD = "root";

    HikariDataSource dataSource = null;

    {
        //1.创建HikariCP配置
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(this.JDBC_URL);
        config.setUsername(JDBC_USER);
        config.setPassword(JDBC_PASSWORD);
        config.setMaximumPoolSize(10);
        config.setIdleTimeout(30000);
        config.setMaxLifetime(1800000);

        //2.创建HikariCP数据源
        dataSource = new HikariDataSource(config);
    }

    @Test
    public void testHirka(){
        //3.从连接池获取连接
        try(Connection connection = dataSource.getConnection()){
            System.out.println("数据库连接成功");
            //执行数据库操作
            String sql = "SELECT * FROM students WHERE id = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1 , 1);
            ResultSet resultSet = statement.executeQuery();
            while ( resultSet.next()){
                long id = resultSet.getLong(1);//注意  这里的索引是从1开始的
                String name = resultSet.getString(2);
                int gender = resultSet.getInt(3);
                int grade = resultSet.getInt(4);
                int score = resultSet.getInt(5);
                System.out.println(id + " " + name + " " + gender + " " + grade + " " + score);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

}
